package cn.jdemo.ref.PhantomReference;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Demo02 {

    /**
     * 输出:
     * null	list add ok
     * null	list add ok
     * null	list add ok
     * null	list add ok
     * Exception in thread "t1" java.lang.OutOfMemoryError: Java heap space
     * 	at cn.jdemo.ref.PhantomReference.Demo02.lambda$main$0(Demo02.java:26)
     * 	at cn.jdemo.ref.PhantomReference.Demo02$$Lambda$1/1792845110.run(Unknown Source)
     * 	at java.lang.Thread.run(Thread.java:748)
     * -----有虚对象回收加入了队列
     */
    public static void main(String[] args) {
        //设置jvm启动参数，内存10M
        Demo02 myObject = new Demo02();
        ReferenceQueue<Demo02> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Demo02> phantomReference = new PhantomReference<>(myObject,referenceQueue);
        //System.out.println(phantomReference.get());  //PhantomReference的get方法总是返回null

        List<byte[]> list = new ArrayList<>();

        new Thread(() -> {
            while (true){
                list.add(new byte[1 * 1024 * 1024]);
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(phantomReference.get()+"\t"+"list add ok");
            }
        },"t1").start();

        new Thread(() -> {
            while (true){
                Reference<? extends Demo02> reference = referenceQueue.poll();
                if(reference != null){
                    System.out.println("-----有虚对象回收加入了队列");
                    break;
                }
            }
        },"t2").start();
    }
}
